package edu.dev.tfile.service;

import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import edu.dev.tfile.common.Utils;

public class UploadPathService extends HttpServlet {

	private static final long serialVersionUID = 530253177694008391L;

	private static String basePath = Utils.getConfig("upload_path");

	private static final String BASE_URI = "/upath";

	private List<String> ignoreList = new ArrayList<String>();

	private boolean displayHiddenFolder = false;

	public UploadPathService() {
		String flagStr = Utils.getConfig("display_hidden_folder");
		displayHiddenFolder = flagStr.equalsIgnoreCase("true");
		String ignoreStr = Utils.getConfig("ignore_folder_name");
		for (String name : ignoreStr.split("\\|")) {
			ignoreList.add(name.toUpperCase());
		}

	}

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String appendUri = req.getRequestURI();
		appendUri = URLDecoder.decode(appendUri, "UTF-8");
		String path = "";
		if (BASE_URI.equals(appendUri)) {
			path = basePath;
		} else {
			path = basePath + appendUri.substring(BASE_URI.length());
		}
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		File currentFile = new File(path);
		if (!currentFile.exists()) {
			Utils.sendMsg(resp, Utils.getJSON(list));
		} else if (currentFile.isDirectory()) {
			if (!"/".equals(appendUri.substring(appendUri.length() - 1))) {
				appendUri = appendUri + "/";
			}
			File[] files = currentFile.listFiles(new FileFilter() {
				@Override
				public boolean accept(File file) {
					if (file.isDirectory() && (!file.isHidden() || displayHiddenFolder)) {
						String name = file.getName();
						return !ignoreList.contains(name.toUpperCase());
					}
					return false;
				}
			});
			for (File file : files) {
				list.add(getFileAttr(file, appendUri));
			}
			Utils.sendMsg(resp, Utils.getJSON(list));
		} else if (currentFile.isFile()) {
			Utils.sendMsg(resp, Utils.getJSON(list));
		}
	}

	private Map<String, Object> getFileAttr(File file, String uri) {
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("name", file.getName());
		map.put("path", uri + file.getName());
		return map;
	}

}
